<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,
   				 width=device-width,initial-scale=1.0" />
		<title>物联网平台</title>
		<link rel="shortcut icon" href="/visual/favicon.ico" type="image/x-icon">
		<!--<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" />-->
		<link rel="stylesheet" href="lib/jquery-ui/jquery-ui.min.css" />
<!--		<link rel="stylesheet" href="//unpkg.com/element-ui@2.15.9/lib/theme-chalk/index.css">-->
		<link rel="stylesheet" href="lib/element-ui/index.css">
		<script type="text/javascript" src="/visual/hlsjs/hls.min.js"></script>
		<script type="text/javascript" src="/visual/flv/flv.min.js"></script>
		<script src="lib/element-ui/vue.min.js"></script>
<!--		<script src="//unpkg.com/element-ui@2.15.9/lib/index.js"></script>-->
		<script src="lib/element-ui/index.js"></script>
        <script src="js/util.js"></script>
		<script type="text/javascript" src="./lib/jquery/jquery.min.js"></script>

		<script type="text/javascript" src="./lib/layer/layer.js"></script>

<!--		<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=DmdxAiL3haaCrI0M3NXIMu2fMEPWelrE"></script>-->
		<!-- 视频播放 -->
		<script src="https://open.ys7.com/sdk/js/1.3/ezuikit.js"></script>

		<script type="text/jscript" src="lib/jquery-ui/jquery-ui.min.js"></script>
<!--        <script type="text/javascript" src="./echarts/echarts.common.min.js"></script>-->
        <script type="text/javascript" src="./echarts/echarts.min.js"></script>
        <!--<script type="text/javascript" src="//lib.baomitu.com/echarts/5.3.3/echarts.common.js"></script>-->
        <script type="text/javascript" src="./echarts/echarts-liquidfill.min.js"></script>
		<!--<script type="text/jscript" src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>-->
		<script type="text/javascript" src="js/show.js"></script>
		<link rel="stylesheet" href="css/show.css" />
		<script type="text/javascript" src="/visual/lib/base64.min.js"></script>
        <style>
            @media screen and (orientation: portrait) {
                html{
                    width : 100% ;
                    height : 100% ;
                    overflow : hidden;
                }
                #PCbody{
                    position : absolute ;
                    width : 100% ;
                    height : 100% ;
                    overflow : hidden;
                }
            }
            @media screen and (orientation: landscape) {
                html{
                    width : 100% ;
                    height : 100% ;
                }
                #PCbody{
                    position : absolute ;
                    top : 0 ;
                    left : 0 ;
                    width : 100% ;
                    height : 100% ;
                }
            }
        </style>
	</head>
	<body id="PCbody">
		<div id="appps">
			<div id="app">
			</div>

			<el-dialog title="数据下发" :visible.sync="dialogVisible" :width="popwidth" >
			  <el-input v-model="inputData" size="medium" placeholder="请输入数据"></el-input>
			  <span slot="footer" class="dialog-footer">
			    <el-button @click="dialogVisible = false">取 消</el-button>
			    <el-button type="primary" @click="downdata">确 定</el-button>
			  </span>
			</el-dialog>

			<el-dialog title="数据下发" :visible.sync="dialogVisibleTime" :width="popwidth">
                <el-time-picker
                        style="width: 100%"
                        v-model="inputData"
                        size="medium"
                        editable="false"
                        value-format="HH:mm"
                        format="HH:mm"
                        align="center"
                        :picker-options="{selectableRange: '00:00:00 - 23:59:00',format:'HH:mm'}"
                        placeholder="任意时间点"></el-time-picker>
			  <span slot="footer" class="dialog-footer">
			    <el-button @click="dialogVisibleTime = false">取 消</el-button>
			    <el-button type="primary" @click="downdata('time')">确 定</el-button>
			  </span>
			</el-dialog>

		</div>
		<div class="operateColumn"  id="disTypeDiv" hidden="hidden">
			<img src="./image/scale_d.png" onclick="scaled()">
			<img src="./image/scale_x.png" onclick="scalex()">
			<img src="./image/scale_n.png" onclick="scalen()">
		</div>
	</body>
    <script type="text/javascript">
		var id={}
	 	id.id= getQueryString('id') ;
		var keyCode = getQueryString('keyCode') ;
		var access_token = getQueryString("access_token");
		var code = getQueryString("code");
		var secret = getQueryString("secret");
		var deviceId = getQueryString("deviceId");
		var username = getQueryString("text1");
		var password = getQueryString("text2");
		var app = new Vue({
    		el:"#appps",
			data:function(){
				return {
					isdrag:false,
                    wsTimer:"",
					dialogVisible: false ,
					dialogVisibleTime: false ,
					textTitle:"",
					downDevCode : '' ,
                    downNowValue : '' ,
					downFieldName : '' ,
                    downFatherFieldName:'',
                    childValueType:'',
					downValueType : '' ,
					inputData: '' ,
					tabmode:0,
					uploadImgs:[],
					initUpload:'',
					uploadImgCount:0,
					sensorMap:{},
					videoMap:{},
					nid:'',				//当前选择对象n类型
					sid:'',
					sensor_id:'',
                    sensor_id_father:'',
					isModbus:false,
					device_slave_id:'',
					node_id:'',
					cid:'',
					video_id:'',
					bdMap:{}, 			//节点id-map对象
					chartMap:{} ,		//
					scaler:1 ,			// 放大缩小
					changescaler: 1 ,   // 变化
					orginWidth: '' ,    // 组件的宽度
					orginHeight:'' ,    // 组件的高度
					client: '' ,
					scene_id: '' ,
					devCode: '' ,		// 设备id
                    farmId: '' ,
                    greenHouseId: '' ,
					lastTime: new Date().getTime() ,
					popwidth: '',   // 弹窗宽度,
					disType: '',   // 手机或 电脑,
					ws:'',
					alarmWs:'',
				};
			},
			methods:{
                closeWs(){
                    if(this.ws){
                        this.ws.close();
                        let _this=this
                        this.ws.onclose = function(evt) {
                            console.log("websocket已关闭");
                        };
                    }
                    if(this.alarmWs){
                        this.alarmWs.close();
                        let _this=this
                        this.alarmWs.onclose = function(evt) {
                            console.log("websocket已关闭");
                        };
                    }
                },
				initVisualInfo(){	//初始化组态数据
                    var that = this;
                    let token = localStorage.getItem("TOKEN");
                    if (token == null || token == 'null'){
                        if (username!=null && password!=null ){
                            $.ajax({
                                type: "POST",
                                url: iotbaseurl + 'api/v1/loginCompany',
                                data: {
                                    "password":fromCode(password),
                                    "userName":fromCode(username)
                                },
                                success: function (e) {
                                    if (e.Code==0){
                                        localStorage.setItem("TOKEN",e.Data.Token)
                                        that.initInfo()
                                    }else{
                                        localStorage.setItem("TOKEN",null)
                                        that.$message.error("登录错误请联系管理员！")
                                        setTimeout(()=>{
                                            window.open(`./login.html?keyCode=${keyCode}`,'_self');
                                        },1500)
                                    }
                                }
                            });
                        }else {
                           window.open(`./login.html?keyCode=${keyCode}`,'_self');
                        }
                    }else{
                        that.initInfo()
                    }
				},
                initInfo(){
                    var that = this;
                    if( keyCode != null){
                        commonAjax('GET',baseurl+'yesiot/visual/display?keycode=' + keyCode, '',function(e){
                            if(e){
                                var data=e;
                                document.title= e.name ;
                                that.scene_id = e.sceneId ;
                                that.farmId = e.farmId ;
                                that.greenHouseId = e.greenHouseId ;
                                that.devCode = e.devCode ;

                                // console.log(e.disType)
                                // 0 是电脑、1是手机
                                if(e.disType === 0){
                                    if (navigator.userAgent.match(/Mobile|Android/i)) {
                                       // console.log('PC手机预览需要横屏')
                                        var width = document.documentElement.clientWidth;
                                        var height =  document.documentElement.clientHeight;
                                        $print =  $('#PCbody');
                                        $print.width(height);
                                        $print.height(width);
                                        $print.css('top',  (height-width)/2 );
                                        $print.css('left',  0-(height-width)/2 );
                                        $print.css('transform' , 'rotate(90deg)');
                                        $print.css('transform-origin' , '50% 50%');

                                    }
                                }

                                $("#app").html(data.content);

                                if (e.model==="1"){
                                    reinitDiv(e.devCode)
                                }
                                // chart 初始化
                                reinitChartObj();
                                // 初始化实时数据
                                if (e.model==="1"){
                                    websocketBaseData(e.devCode);
                                }else{
                                    initBaseData() ;
                                }
                                initVideo(e.model,e.devCode);
                                that.disType=data.disType;
                                that.initCanvasStyle();
                                //initMap();
                                initTextOrTime();
                                //that.mqttInit();
                                // 初始化设备状态
                                initDeviceStatus();
                                //刷新token
                                setInterval(refreshToken(),3000000)
                                //预警
                                var alarmEnable = $(".edit-container").attr("alarmEnable") ;
                                if (alarmEnable==='true'){
                                    alarmWebsocket(e.model)
                                }
                                if(data.disType == 1 ){
                                    that.popwidth = '80%' ;
                                }else{
                                    //$("#disTypeDiv").removeAttr("hidden")
                                    that.popwidth = '30%' ;
                                }
                            }
                        });
                    }
                },
				async downdata(time) {
                    if (time == 'time') {
                        app.inputData = app.inputData.toString().replace(":", "")
                    }
                    try {
                        layer.load(2)
                        let inputData=app.inputData
                        let downNowValue= app.downNowValue
                        let downFieldName=app.downFieldName
                        let childValueType=app.childValueType
                        if (childValueType!=null){
                            inputData = conversionType(childValueType,inputData);
                        }

                        console.log(childValueType)
                        let data={
                            downFieldName : inputData
                        }

                        console.log(data)
                        await commonAjax('POST', iotbaseurl + 'api/v1/dev/SetProperty', {
                            DevCode: app.downDevCode,
                            FieldName : app.downFatherFieldName ,
                            Value:  app.downValueType==='struct'?JSON.stringify(data):inputData,
                            ValueType: app.downValueType
                        }, async function (data) {
                            if (data) {
                                if (data.Code == -1) {
                                    app.$message.error(data.Message);
                                } else {
                                    let isTrue = ""
                                    let ceshiNum = 0
                                    let timer = await setInterval(async () => {
                                        if(isTrue!=="" || ceshiNum === 10){
                                            layer.closeAll()
                                            clearInterval(timer)

                                            if (time == 'time'){
                                                isTrue=parseInt(isTrue)
                                                inputData=parseInt(inputData)
                                                downNowValue=parseInt(downNowValue)
                                            }
                                            if (isTrue===inputData) {
                                            } else if (isTrue!=inputData&&isTrue!=downNowValue) {
                                            }else if (ceshiNum === 10){
                                            }
                                        }else{
                                            isTrue = await contrastAttribute(app.downDevCode, app.downFieldName, app.inputData);
                                        }
                                        ceshiNum ++
                                    },500)
                                }
                                app.inputData = '';
                                app.dialogVisible = false;
                            }
                        })
                    } catch (error) {
                        console.error(error);
                    }
                },
				//初始化样式
				initCanvasStyle(){
					var xr = 1 ;
					// 屏幕宽度
					var win_width = $(window).width() ;
					var win_height = $(window).height() ;

					// 组态高度
					var content_width = $(".edit-container").width();
					var content_height = $(".edit-container").height();

					this.orginWidth  = content_width ;
					this.orginHeight = content_height ;

					let r = win_width / content_width ;
 					let h = win_height / content_height ;
					if (this.disType == 1){
						xr=r
					}else{
						xr = r>h?h:r ;
					}
					this.scaler = xr ;
					this.changescaler = xr ;
//					win_width-content_width*xr/2;
					var translatewidth = ((win_width-content_width*xr)/2) ;
					var translateheight =  0 ;

					$(".edit-container").css({
				   		"-webkit-transform":"scale(" + xr + ", "+ xr +" ) translate("+translatewidth+"px,"+translateheight+"px)",
				   		"transform":"scale(" + xr + ", "+ xr +" ) translate("+translatewidth+"px,"+translateheight+"px)",
				   		"position":"relative",
				   		"transform-origin":"0 0",
				   		"margin-left":"0",
                        "left":'0',
                        "top":'0',
				   	});

                    if(this.disType === 0){
                        if (navigator.userAgent.match(/Mobile|Android/i)) {
                            let newLeft = win_height - content_height*xr
                            $(".edit-container").css({
                                "left":`${newLeft /2}px`
                            });
                        }
                    }

					// 这里把背景色或者背景图片，更换下
					var bg = $(".edit-container").attr("bg") ;
					if(isNotEmpty(bg)){
						$("body").css("background-color",bg) ;
					}

					var url =  $(".edit-container").attr("bgurl") ;
					if(isNotEmpty(url)){
						$("body").css("background","url("+ url +")  no-repeat ") ;
						$("body").css("background-position","center top") ;
					}
				},
				mqttInit(){
                	/*var that = this ;
                	// 连接选项
                	var client = this.client ;
                	const options = {
                	      connectTimeout: 4000, // 超时时间
                	      // 认证信息
                	      clientId: 'brower_' + parseInt(Math.random()/31.1*10000000000),
                	      username: mqttUserName ,
                	      password: mqttPassword ,
                	}
                	client = mqtt.connect('ws://'+document.domain+':8083/mqtt', options) ;
                	client.on('reconnect', function(error)  {
                		console.log("reconnect");
                	})
                	client.on('error', function(error) {
                	    console.log('连接失败:', error)
                	})
                	client.on('message', function(topic, message,s) {
                		if( message.toString() == '1' ){
                			if( that.lastTime + 2*1000 < new Date().getTime() ){
                				that.lastTime = new Date().getTime() ;

                				udpChartValue();
                				initSensorData();
                				initControlNode();
                				initStateNode() ;
                				initDeviceStatus();
                			}
                		}
                	})
                	client.subscribe("/scene/update/"+ that.scene_id );
            		client.publish('/sys/update/scene' , that.scene_id+'' );*/
                }
			},created(){
                window.addEventListener('beforeunload', e => this.closeWs(e))
			},mounted() {
                this.initVisualInfo();
                $(window).resize(function() {
                    app.initCanvasStyle();
                });
            },beforeDestroy(){
                window.addEventListener('beforeunload', e => this.closeWs(e))
            }
    	})
    </script>

</html>
